<template>
	<div id="admin">
		<el-container>
			<div class="top">
				<el-input placeholder="请输入管理员名称" v-model="lookrole" clearable></el-input>
				<el-button type="primary" icon="el-icon-search" @click="lookup">查找</el-button>
				<el-button type="primary" icon="el-icon-edit" @click="dialogFormVisible = true">添加</el-button>
				<el-button type="primary" icon="el-icon-download">导出</el-button>
			</div>
			<el-main>
				<el-table :data="tableData" border stripe style="width: 100%">
					<el-table-column prop="id" label="管理员ID" sortable></el-table-column>
					<el-table-column prop="username" label="管理员名称"></el-table-column>
					<el-table-column label="管理员头像">
						<template slot-scope="scope">
							<img :src="scope.row.avatar" style="width: 40px;height: 30px;">
						</template>
					</el-table-column>
					<el-table-column label="管理员角色" prop="roleName">
						<template slot-scope="scope">
							<el-tag size="medium" v-for="(item,index) in scope.row.roleName">{{item}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="operation" label="操作">
						<template slot-scope="scope">
							<el-button size="mini" type="primary" @click="getData(scope.$index, scope.row),dialogEditVisible = true">编辑</el-button>
							<el-button size="mini" type="danger" @click="deletes(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-main>
			<!-- 添加 -->
			<el-dialog title="创建" :visible.sync="dialogFormVisible" width="600px">
				<el-form :model="form" >
					<el-form-item prop="username" label="管理员名称" :label-width="formLabelWidth" :rules="[
					{ required: true, message: '管理员名称不能为空', trigger: 'blur' }]">
						<el-input autocomplete="off" v-model="form.username"></el-input>
					</el-form-item>
					<el-form-item prop="password" label="管理员密码" :label-width="formLabelWidth" :rules="[
					{ required: true, message: '密码不能为空', trigger: 'blur' }]">
						<el-input type="password" autocomplete="off" v-model="form.password"></el-input>
					</el-form-item>
					<el-form-item label="管理员头像" :label-width="formLabelWidth">
						<el-upload
						  :headers="token" class="avatar-uploader"
						  	action="http://192.168.1.54:8080/admin/storage/create" :show-file-list="false"
						  	:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
						  <img v-if="imageUrl" :src="imageUrl" class="avatar">
						  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</el-form-item>
					<el-form-item label="管理员角色" :label-width="formLabelWidth">
					    <el-select v-model="form.region" :multiple="true">
					    	<el-option v-for="(item,index) in form.selects" :label="item.name" :value="item.id">
					    		{{item.name}}
					    	</el-option>
					    </el-select>
					  </el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取 消</el-button>
					<el-button type="primary" @click="creates">确 定</el-button>
				</div>
			</el-dialog>
			<!-- 修改 -->
			<el-dialog title="编辑" :visible.sync="dialogEditVisible">
				<el-form :model="edits">
					<el-form-item prop="username" label="管理员名称" :label-width="formLabelWidth" :rules="[
					{ required: true, message: '管理员名称不能为空', trigger: 'blur' }]">
						<el-input autocomplete="off" v-model="edits.name"></el-input>
					</el-form-item>
					<el-form-item prop="password" label="管理员密码" :label-width="formLabelWidth" :rules="[
					{ required: true, message: '密码不能为空', trigger: 'blur' }]">
						<el-input type="password" autocomplete="off" v-model="edits.pwd"></el-input>
					</el-form-item>
					<el-form-item label="管理员头像" :label-width="formLabelWidth">
						<el-upload :headers="token" class="avatar-uploader"
							action="http://192.168.1.54:8080/admin/storage/create" :show-file-list="false"
							:on-success="handleAvatarSuccessdd" :before-upload="beforeAvatarUpload">
							<img v-if="imageUrls" :src="imageUrls" class="avatar">
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</el-form-item>
					<el-form-item label="管理员角色" :label-width="formLabelWidth">
						<el-select v-model="edits.regions" :multiple="true">
							<el-option v-for="(item,index) in form.selects" :label="item.name" :value="item.id">
								{{item.name}}
							</el-option>
						</el-select>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogEditVisible = false">取 消</el-button>
					<el-button type="primary" @click="edit">确 定</el-button>
				</div>
			</el-dialog>
			<!-- 分页 -->
			<el-footer>
				<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:page-sizes="[10, 20, 30, 40,50,100]" :page-size="10" layout="total, sizes, prev, pager, next, jumper"
				:total="totalData">
				</el-pagination>
			</el-footer>
		</el-container>
	</div>
</template>

<script>
import {
		list, // 列表渲染
		seek,// 查找
		addition,// 添加
		compile,// 编辑
		remove,// 删除
		paging,// 分页
		pagingsa, // 分页数据
		adminrole // 管理员角色
	} from '@/api/http.js'
	import cookies from 'js-cookie'
	export default {
		data() {
			return {
				token: {
					'X-Litemall-Admin-Token': this.$cookie.get("tokens")
				},
				tableData: [],
				imageUrl: '', //添加上传头像
				imageUrls: '', //编辑头像
				dialogFormVisible: false, //控制添加弹窗
				dialogEditVisible: false, //控制编辑弹窗
				formLabelWidth: '120px',
				lookrole: '', //查找管理员
				totalData: 0, //分页数据
				tree: [], //权限数据
				form: { //添加
					username: '',
					password: '',
					region: [], //保存数组
					selects: "" //读取选项数据
				},
				edits: { //编辑
					id: '',
					name: '',
					pwd: '',
					regions: [],
					selects: ""
				},
			}
		},
		mounted() {
			this.getAdmin(); // 角色管理列表渲染
			this.eloption(); //获取选项数据
		},

		methods: {
			// 管理员列表渲染
			getAdmin() {
				list().then((res) => {
					this.tableData = res.data.data.list
					this.totalData = res.data.data.total
					//循环角色列表读取数据
					for (var i = 0; i < this.tableData.length; i++) {
						this.tableData[i].roleName = []
						if (this.tableData[i].roleIds.length > 0) {
							for (var k = 0; k < this.tableData[i].roleIds.length; k++) {
								for (var j = 0; j < this.form.selects.length; j++) {
									if (this.form.selects[j].id == this.tableData[i].roleIds[k]) {
										this.tableData[i].roleName.push(this.form.selects[j].name)
									}
								}
							}
						}
					}
				})
			},
			eloption() { //获取选项数据
				let obj = {
					limit: this.totalData
				}
				adminrole(obj).then((res) => {
					this.form.selects = res.data.data.list
					this.getAdmin()
				})
			},
			// 上传头像
			handleAvatarSuccess(res, file) {
				this.imageUrl = res.data.url
			},
			// 编辑头像
			handleAvatarSuccessdd(res, file) {
				this.imageUrls = res.data.url
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			// 查找
			lookup() {
				seek(this.lookrole).then(res => {
					this.tableData = res.data.data.list
				})
			},
			// 添加
			creates() {
				let addadmin = {
					username: this.form.username,
					password: this.form.password,
					avatar: this.imageUrl,
					roleIds: this.form.region,
				}
				addition(addadmin).then(res => {
					if (res.data.errmsg == "成功") {
						this.$notify({
							title: '成功',
							message: '添加管理员成功',
							type: 'success'
						});
						this.getAdmin();
						this.form.username = ''
						this.form.password = ''
						this.imageUrl = ''
						this.form.region = ''
					} else {
						this.$notify({
							title: '失败',
							message: '添加失败，管理员已存在！',
							type: 'error'
						});
					}
				}).catch(err => {
					console.log("失败")
				})
				this.dialogFormVisible = false
			},
			// 编辑
			getData(index, row) {
				this.edits.id = row.id,
					this.edits.name = row.username
				this.edits.pwd = row.password
				this.imageUrls = row.avatar
				this.edits.regions = row.roleIds
				console.log(this.edits.regions)
			},
			edit() {
				let obj = {
					id: this.edits.id,
					username: this.edits.name,
					password: this.edits.pwd,
					avatar: this.imageUrls,
					roleIds: this.edits.regions,
				}
				compile(obj).then(res => {
					this.$notify({
						title: '成功',
						message: '更新管理员成功',
						type: 'success'
					});
					this.getAdmin();
				}).catch(err => {
					console.log("失败")
				})
				this.edits.name = '';
				this.edits.pwd = '';
				this.dialogEditVisible = false
			},
			// 删除
			deletes(idnex, row) {
				this.$confirm('是否删除此管理员?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let dels = {
						id: row.id,
						username: row.username,
						password: row.password,
						avatar: row.avatar,
						roleIds: row.roleIds,
					}
					remove(dels).then((res) => {
						this.$notify({
							title: '成功',
							message: '删除管理员成功',
							type: 'success'
						});
						this.getAdmin();
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			// 分页
			handleCurrentChange(page) {
				paging(page).then((res) => {
					this.tableData = res.data.data.list
				})
			},
			handleSizeChange(num) {
				pagingas(num).then((res) => {
					this.tableData = res.data.data.list
				})
			},
		},
	}
</script>

<style>
	#admin .top {
		line-height: 40px;
		height: 40px !important;
		margin-bottom: 20px;
	}

	#admin .top .el-input {
		width: 200px;
		margin-right: 10px;
	}

	#admin .el-form-item .el-input {
		width: 300px;
	}
	
	#admin .el-main {
		padding-bottom: 5px;
	}

	#admin .el-table__body tr .cell {
		text-align: center;
	}

	#admin .has-gutter tr th {
		text-align: center;
	}

	#admin .el-footer {
		border-bottom: 0px;
	}

	#admin .el-form-item {
		color: #373737;
	}
	#admin .avatar-uploader .el-upload {
	  border: 1px dashed #d9d9d9;
	  border-radius: 6px;
	  cursor: pointer;
	  position: relative;
	  overflow: hidden;
	}
	#admin .avatar-uploader .el-upload:hover {
	  border-color: #409EFF;
	}
	#admin .avatar-uploader-icon {
	  font-size: 25px;
	  color: #8c939d;
	  width: 100px;
	  height: 100px;
	  line-height: 100px;
	  text-align: center;
	}
	#admin .avatar {
	  width: 100px;
	  height: 100px;
	  display: block;
	}
</style>
